<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/roles' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addJuese1">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item, i) in scope.row.children" :key="item.id" class="bor">
              <!-- 渲染一级 -->
              <el-col :span="5">
                <el-tag closable @close="delById(scope.row, item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span='19'>
                <!-- 渲染二三级 -->
                <el-row v-for="(item1, i1) in item.children" :key="item1.id" class="flex">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="delById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item2, i2) in item1.children" :key="item2.id" closable
                      @close="delById(scope.row, item2.id)">
                      {{ item2.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="bj(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="delRole(scope.row.id)">删除</el-button>
            <el-button type="success" size="mini" @click="shadow(scope.row)">权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限分配页面 -->
    <el-dialog title="分配权限" :visible.sync="setShadow" width="50%" @close="ifClose">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="defaultProps" @node-click="handleNodeClick" show-checkbox node-key="id"
        default-expand-all :default-checked-keys="checkedKeys" ref="treeRef"></el-tree>


      <span slot="footer">
        <el-button @click="setShadow = false">取消</el-button>
        <el-button type="primary" @click="addRights">确定</el-button>
      </span>
    </el-dialog>
    <!-- 角色编辑页面 -->
    <el-dialog title="编辑角色" :visible.sync="b1" width="50%" @close="bjClose">
      <el-form :model="editForm" label-width="100px" ref="ref2">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="b1 = false">取消</el-button>
        <el-button type="primary" @click="bj1">确定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色页面 -->
    <el-dialog  title="添加角色" :visible.sync="addJuese" width="50%" @close="addClose">
      <el-form  label-width="100px" ref="ref1"  :model="editForm" :rules="rules1" >
        <el-form-item    label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item  label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addJuese = false">取消</el-button>
        <el-button type="primary" @click="addJuese2">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WorkspaceJsonRoles',

  data () {
    return {
      addJuese: false,
      //所有角色列表数据
      rolesList: [],
      setShadow: false,
      // 所有权限数据
      rightsList: [],
      //树形控件的配置对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      //默认选中的节点
      checkedKeys: [],
      roleId: '',
      //编辑角色对话框
      b1: false,
      //角色编辑表单对象
      editForm: {
        roleName: '',
        roleDesc: '',
      },
      rules1: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]{2,12}$/,message: '仅支持中文2-12位字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {pattern: /^[\u4e00-\u9fa5]{2,12}$/, message:'长度在 3 到 12 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created () {
    this.getRolesList();
  },

  mounted () {

  },

  methods: {
    //获取所有角色列表
    getRolesList () {
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取角色列表失败');
        this.rolesList = res.data.data;
      });
    },
    //获取角色列表
    addJuese1 () {
      this.addJuese=true;
    },

    // 添加角色
    addJuese2 () {
     
      this.$refs.ref1.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的信息');
      this.$http.post('roles', {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc,
      }).then(res => {
        if (res.data.meta.status !== 201) return this.$message.error('添加角色失败');
        this.$message.success('添加角色成功');
        this.getRolesList();
        this.addJuese=false;
      });
      });
     


      
    },
    //根据id删除权限
    delById (id, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete(`roles/${id.id}/rights/${rightId}`).then(res => {
          if (res.data.meta.status !== 200) return this.$message.error('删除权限失败');
          this.$message.success('删除权限成功');
          // this.getRolesList();
          id.children = res.data.data
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //展开分配权限的对话框,打印keys
    async shadow (role) {
      this.roleId = role.id
      //获取所有数据权限列表
      await this.$http.get('rights/tree').then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取权限列表失败');
        this.$message.success('获取权限列表成功');
        console.log(res.data.data);
        this.rightsList = res.data.data
        this.saveId(role, this.checkedKeys)
        console.log(this.checkedKeys);
        this.setShadow = true
      });


    },
    handleNodeClick () {
      console.log(111);
    },
    //递归,获取所有三级权限id并保存到数组中
    saveId (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.saveId(item, arr)
        })
      }
    },
    //监听对话框关闭事件
    ifClose () {
      this.checkedKeys = []
    },
    //点击分配权限按钮,发送请求,分配权限
    addRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //拼接成字符串
      const str = keys.join(',')
      // console.log(str);
      //请求  /roles/:roleId/rights
      this.$http.post(`roles/${this.roleId}/rights`, {
        rids: str
      }).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('分配权限失败')
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.setShadow = false
      })
    },
    //删除角色
    delRole (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete(`roles/${id}`).then(res => {
          if (res.data.meta.status !== 200) return this.$message.error('删除角色失败');
          this.$message.success('删除角色成功');
          this.getRolesList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //编辑修改角色
    async bj (id) {
     
      //根据id查询角色
      await this.$http.get(`roles/${id}`).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取角色失败')
        this.$message.success('获取角色成功')
        this.editForm = res.data.data

        //console.log(this.editForm);
        this.editForm.roleName = ''
        this.editForm.roleDesc = ''
        this.b1 = true
      })

    },
    //监听添加角色对话框关闭事件
    addClose () {
        this.editForm.roleName = ''
        this.editForm.roleDesc = ''

    },
    //监听编辑角色关闭页面事件
    bjClose () {
      this.rolesList.roleName = ''
      this.rolesList.roleDesc = ''
    },
    //点击确定按钮,发送请求,修改角色
    bj1 () {
      this.$http.put(`roles/${this.editForm.roleId}`, {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc
      }).then(res => {
        // console.log(res)
        if (res.data.meta.status !== 200) return this.$message.error('修改角色失败')
        this.$message.success('修改角色成功')
        this.getRolesList()
       
        
        this.b1 = false
      })
    }







    //方法结尾
  },
};
</script>

<style lang="less" scoped></style>